<template>
  <div class="menu-manage-container">
    <!-- 页面标题 + 操作栏（移除面包屑中的“系统管理”） -->
    <div class="page-header">
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <!-- 移除“系统管理”面包屑项，直接显示“菜单管理” -->
        <el-breadcrumb-item>菜单管理</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="operation-bar">
        <el-input
            v-model="searchValue"
            placeholder="请输入菜单名称/路径/权限编码搜索"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
            style="width: 280px; height: 36px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" size="small" style="height: 100%; border-left: none;" />
          </template>
        </el-input>

        <el-button
            type="primary"
            @click="handleAddMenu"
            icon="el-icon-plus"
            size="small"
            style="margin-left: 10px;"
        >
          新增
        </el-button>

        <el-button
            type="warning"
            @click="toggleExpandAll"
            :icon="allExpanded ? Expand : Collapse"
            size="small"
            style="margin-left: 10px;"
        >
          {{ allExpanded ? '全部折叠' : '全部展开' }}
        </el-button>
      </div>
    </div>

    <!-- 菜单表格（删除目录/菜单的图标区分） -->
    <el-card class="table-card" shadow="hover">
      <el-skeleton v-if="loading" row-count="6" :columns="8" border></el-skeleton>

      <el-table
          v-else
          :data="filteredMenuList"
          style="width: 100%; font-size: 13px;"
          stripe
          border
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          row-key="menuId"
          tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :expand-row-keys="expandRowKeys"
          @expand-change="handleExpandChange"
          size="mini"
      >
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>

        <!-- 菜单名称（仅保留层级缩进，删除图标区分） -->
        <el-table-column prop="name" label="菜单名称" min-width="120">
          <template #default="{ row, level }">
            <div class="menu-name-wrapper" :style="{ paddingLeft: level * 20 + 'px' }">
              <!-- 仅保留菜单名称，删除 Folder/Document 图标 -->
              <span class="menu-name">{{ row.name }}</span>
              <!-- 保留状态标签 -->
              <el-tag v-if="row.hidden" size="mini" type="info" style="margin-left: 8px;">隐藏</el-tag>
              <el-tag v-if="row.isDeleted" size="mini" type="danger" style="margin-left: 8px;">已删除</el-tag>
            </div>
          </template>
        </el-table-column>

        <!-- 路径 -->
        <el-table-column prop="path" label="路由路径" min-width="80" align="center"></el-table-column>

        <!-- 组件 -->
        <el-table-column prop="component" label="组件路径" min-width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.component || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 权限编码 -->
        <el-table-column prop="permissionCode" label="权限编码" min-width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.permissionCode || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 图标 -->
        <el-table-column prop="icon" label="菜单图标" width="100" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :class="row.icon" size="18"></el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="hidden" label="状态" width="200" align="center">
          <template #default="{ row }">
            <el-switch
                v-model="row.hidden"
                active-color="#f56c6c"
                inactive-color="#67c23a"
                active-text="隐藏"
                inactive-text="显示"
                @change="handleStatusChange(row)"
                size="mini"
            ></el-switch>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" min-width="220" align="center">
          <template #default="{ row }">
            <el-button
                type="text"
                size="mini"
                @click.stop="handleAddSubMenu(row)"
                :disabled="row.isDeleted"
                class="oper-btn add-btn"
            >
              <el-icon size="14"><Plus /></el-icon> 新增子菜单
            </el-button>

            <el-button
                type="text"
                size="mini"
                @click.stop="editMenu(row)"
                :disabled="row.isDeleted"
                class="oper-btn edit-btn"
            >
              <el-icon size="14"><Edit /></el-icon> 编辑
            </el-button>

            <el-button
                type="text"
                size="mini"
                @click.stop="handleDeleteConfirm(row)"
                :disabled="row.isDeleted || (row.children && row.children.length > 0)"
                class="oper-btn delete-btn"
            >
              <el-icon size="14"><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && filteredMenuList.length === 0" class="empty-tip">
        <el-empty description="暂无菜单数据"></el-empty>
      </div>
    </el-card>

    <!-- 菜单编辑/添加对话框（保持不变） -->
    <el-dialog
        v-model="showMenuDialog"
        :title="dialogTitle"
        width="600px"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        destroy-on-close
    >
      <el-form
          :model="menuForm"
          label-width="110px"
          class="menu-form"
          :rules="menuRules"
          ref="menuFormRef"
          size="mini"
      >
        <!-- 菜单ID（编辑时显示） -->
        <el-form-item label="菜单ID" v-if="isEditMode" disabled>
          <el-input v-model="menuForm.menuId" style="width: 100%;"></el-input>
        </el-form-item>

        <!-- 上级菜单（层级选择） -->
        <el-form-item label="上级菜单" prop="parentMenuId">
          <el-select
              v-model="menuForm.parentMenuId"
              placeholder="请选择上级菜单"
              style="width: 100%;"
              :disabled="isSubMenu || menuForm.isDeleted"
              filterable
              clearable
          >
            <el-option
                value="0"
                label="顶级菜单"
            ></el-option>
            <el-option
                v-for="menu in flatMenuList"
                :key="menu.menuId"
                :value="menu.menuId"
                :label="getMenuLevelLabel(menu)"
                :disabled="isEditMode && (menu.menuId === menuForm.menuId || isChildOf(menuForm.menuId, menu.menuId))"
            ></el-option>
          </el-select>
          <div class="form-tip">选择"顶级菜单"创建一级菜单，子菜单会继承上级权限</div>
        </el-form-item>

        <!-- 菜单名称 -->
        <el-form-item label="菜单名称" prop="name">
          <el-input
              v-model="menuForm.name"
              placeholder="请输入菜单名称（如：用户管理）"
              maxlength="128"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
        </el-form-item>

        <!-- 路由路径 -->
        <el-form-item label="路由路径" prop="path">
          <el-input
              v-model="menuForm.path"
              placeholder="请输入路由路径（如：/system/user）"
              maxlength="256"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
          <div class="form-tip">前端路由路径，需与 router/index.js 配置一致</div>
        </el-form-item>

        <!-- 组件路径 -->
        <el-form-item label="组件路径" prop="component">
          <el-input
              v-model="menuForm.component"
              placeholder="请输入组件路径（如：system/user/index）"
              maxlength="128"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
          <div class="form-tip">目录菜单可留空，菜单需填写完整组件路径</div>
        </el-form-item>

        <!-- 权限编码 -->
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input
              v-model="menuForm.permissionCode"
              placeholder="请输入权限编码（如：sys:user:view）"
              maxlength="128"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
          <div class="form-tip">空表示无需权限即可访问，需与权限表编码一致</div>
        </el-form-item>

        <!-- 菜单图标 -->
        <el-form-item label="菜单图标" prop="icon">
          <el-input
              v-model="menuForm.icon"
              placeholder="请输入图标类名（如：el-icon-user）"
              maxlength="64"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
          <div class="form-tip">支持 Element Plus 图标，可参考官网图标库</div>
          <el-icon v-if="menuForm.icon" :class="menuForm.icon" size="20" style="margin-top: 8px;"></el-icon>
        </el-form-item>

        <!-- 排序号 -->
        <el-form-item label="排序号" prop="sort">
          <el-input-number
              v-model="menuForm.sort"
              :min="0"
              :max="999"
              placeholder="排序号"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input-number>
          <div class="form-tip">数字越小，显示越靠前</div>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="menuForm.remark"
              placeholder="请输入备注信息"
              maxlength="256"
              style="width: 100%;"
              type="textarea"
              rows="2"
              :disabled="menuForm.isDeleted"
          ></el-input>
        </el-form-item>

        <!-- 元数据 -->
        <el-form-item label="元数据" prop="metal">
          <el-input
              v-model="menuForm.metal"
              placeholder="请输入元数据（如：用户管理页面）"
              maxlength="256"
              style="width: 100%;"
              :disabled="menuForm.isDeleted"
          ></el-input>
          <div class="form-tip">用于页面标题、面包屑等展示</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="mini" @click="showMenuDialog = false">取消</el-button>
        <el-button size="mini" type="primary" @click="saveMenu" :disabled="menuForm.isDeleted">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框（保持不变） -->
    <el-dialog
        v-model="showDeleteDialog"
        title="删除确认"
        width="350px"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <div class="delete-tip">
        <el-icon size="24" style="color: #f56c6c;"><Warning /></el-icon>
        <p v-if="currentMenu?.children && currentMenu.children.length">
          该菜单包含 <span class="text-danger">{{ countChildMenus(currentMenu) }}</span> 个子菜单，不允许直接删除！
          <br>请先删除所有子菜单后重试。
        </p>
        <p v-else-if="currentMenu?.isDeleted">
          该菜单已处于删除状态，无需重复操作。
        </p>
        <p v-else>
          确定要删除菜单「<span class="text-primary">{{ currentMenu?.name }}</span>」吗？
          <br>删除后将标记为"已删除"状态，可在回收站恢复（若有）。
        </p>
      </div>
      <template #footer>
        <el-button size="mini" @click="showDeleteDialog = false">取消</el-button>
        <el-button
            size="mini"
            type="danger"
            @click="deleteMenu"
            :disabled="currentMenu?.isDeleted || (currentMenu?.children && currentMenu.children.length > 0)"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import httpRequest from "@/config/request";
// 移除不需要的 Folder/Document 图标导入
import {
  Search, Plus, Edit, Delete,
  Expand, Collapse, Warning
} from "@element-plus/icons-vue";

// ==================== 状态管理 ====================
// 菜单数据（直接使用接口返回的树形结构）
const menuList = ref([]); // 原始树形菜单
const flatMenuList = ref([]); // 扁平菜单列表（用于上级菜单选择）
const filteredMenuList = ref([]); // 搜索过滤后的树形菜单
const loading = ref(false);
const searchValue = ref('');

// 树形表格状态
const expandRowKeys = ref([]);
const allExpanded = ref(false);

// 对话框状态
const showMenuDialog = ref(false);
const showDeleteDialog = ref(false);
const isEditMode = ref(false);
const isSubMenu = ref(false);
const currentMenu = ref(null);

// 表单引用与数据
const menuFormRef = ref(null);
const menuForm = reactive({
  menuId: '',
  name: '',
  path: '',
  parentMenuId: 0,
  permissionCode: '',
  component: '',
  hidden: false,
  metal: '',
  icon: '',
  sort: 0,
  remark: '',
  isDeleted: false, // 软删除标识
  tenantId: 0 // 租户ID（适配 BaseModel）
});

// ==================== 配置项 ====================
// 表格样式（RuoYi 风格：浅灰表头，细边框）
const headerCellStyle = {
  background: '#f8f9fa',
  color: '#333',
  fontWeight: 500,
  borderBottom: '1px solid #e9ecef'
};
const cellStyle = {
  color: '#666',
  borderBottom: '1px solid #f0f2f5'
};

// 表单验证规则（强化校验，适配 RuoYi 规范）
const menuRules = reactive({
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { max: 128, message: '菜单名称长度不能超过128个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' },
    { max: 256, message: '路由路径长度不能超过256个字符', trigger: 'blur' },
    { pattern: /^\/[a-zA-Z0-9\/_-]*$/, message: '路由路径必须以"/"开头，仅支持字母、数字、/、_、-', trigger: 'blur' }
  ],
  component: [
    { max: 128, message: '组件路径长度不能超过128个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { max: 128, message: '权限编码长度不能超过128个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9:_]*$/, message: '权限编码仅支持字母、数字、:、_', trigger: 'blur' }
  ],
  icon: [
    { max: 64, message: '图标类名长度不能超过64个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '排序号必须是数字', trigger: 'blur' },
  ],
  metal: [
    { max: 256, message: '元数据长度不能超过256个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 256, message: '备注长度不能超过256个字符', trigger: 'blur' }
  ]
});

// 对话框标题（计算属性：根据模式动态生成）
const dialogTitle = computed(() => {
  if (isEditMode.value) return '编辑菜单';
  if (isSubMenu.value) return `新增【${currentMenu.value?.name}】子菜单`;
  return '新增菜单';
});

// ==================== 核心方法 ====================
/**
 * 初始化：加载菜单数据
 */
const getAllMenus = async () => {
  try {
    loading.value = true;
    const res = await httpRequest.get('menu/list');
    if (res.code ===200 && res.data) {
      // 1. 直接使用接口返回的树形数据（无需手动构建）
      menuList.value = res.data;
      // 2. 生成扁平菜单列表（用于上级菜单选择）
      flatMenuList.value = flattenMenuTree(res.data);
      // 3. 初始化过滤列表
      filteredMenuList.value = [...menuList.value];
      // 4. 默认展开顶级菜单
      initExpandKeys();
    } else {
      ElMessage.error(res.msg || '获取菜单列表失败');
    }
  } catch (error) {
    console.error('加载菜单失败：', error);
    ElMessage.error('加载菜单失败，请刷新页面重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 树形菜单转扁平列表（用于上级菜单选择）
 */
const flattenMenuTree = (menus, result = []) => {
  menus.forEach(menu => {
    // 深拷贝避免原数据污染
    const menuCopy = { ...menu };
    delete menuCopy.children; // 移除children，避免扁平列表冗余
    result.push(menuCopy);
    // 递归处理子菜单
    if (menu.children && menu.children.length) {
      flattenMenuTree(menu.children, result);
    }
  });
  return result;
};

/**
 * 初始化展开的节点（默认展开顶级菜单）
 */
const initExpandKeys = () => {
  const topLevelIds = menuList.value.map(menu => menu.menuId);
  expandRowKeys.value = [...topLevelIds];
  allExpanded.value = topLevelIds.length > 0;
};

/**
 * 搜索过滤（支持树形结构过滤）
 */
const handleSearch = () => {
  const search = searchValue.value.trim().toLowerCase();
  if (!search) {
    filteredMenuList.value = [...menuList.value];
    return;
  }

  // 树形过滤：保留匹配节点及所有父节点
  const filterTree = (menus) => {
    return menus
        .map(menu => {
          const children = filterTree(menu.children || []);
          // 匹配规则：名称/路径/权限编码包含搜索词，或子节点有匹配
          const isMatch =
              menu.name.toLowerCase().includes(search) ||
              (menu.path && menu.path.toLowerCase().includes(search)) ||
              (menu.permissionCode && menu.permissionCode.toLowerCase().includes(search)) ||
              children.length > 0;
          return isMatch ? { ...menu, children } : null;
        })
        .filter(menu => menu !== null);
  };

  filteredMenuList.value = filterTree(menuList.value);
};

/**
 * 切换全部展开/折叠
 */
const toggleExpandAll = () => {
  if (allExpanded.value) {
    // 折叠：清空展开的keys
    expandRowKeys.value = [];
  } else {
    // 展开：获取所有节点的menuId
    const getAllIds = (menus, ids = []) => {
      menus.forEach(menu => {
        ids.push(menu.menuId);
        if (menu.children && menu.children.length) {
          getAllIds(menu.children, ids);
        }
      });
      return ids;
    };
    expandRowKeys.value = getAllIds(menuList.value);
  }
  allExpanded.value = !allExpanded.value;
};

/**
 * 处理节点展开/折叠变化
 */
const handleExpandChange = (row, expanded) => {
  if (expanded) {
    expandRowKeys.value.push(row.menuId);
  } else {
    expandRowKeys.value = expandRowKeys.value.filter(id => id !== row.menuId);
  }
  // 更新全展开状态
  const totalNodes = countAllNodes(menuList.value);
  allExpanded.value = expandRowKeys.value.length === totalNodes;
};

/**
 * 计算所有节点总数
 */
const countAllNodes = (menus) => {
  let count = menus.length;
  menus.forEach(menu => {
    if (menu.children && menu.children.length) {
      count += countAllNodes(menu.children);
    }
  });
  return count;
};

/**
 * 获取菜单层级标签（如：系统管理 > 用户管理）
 */
const getMenuLevelLabel = (menu) => {
  const getParentLabel = (id, labels = []) => {
    const parent = flatMenuList.value.find(m => m.menuId === id);
    if (parent) {
      labels.unshift(parent.name);
      if (parent.parentMenuId !== 0) {
        getParentLabel(parent.parentMenuId, labels);
      }
    }
    return labels;
  };

  const labels = getParentLabel(menu.parentMenuId);
  labels.push(menu.name);
  return labels.join(' > ');
};

/**
 * 检查是否为子菜单关系（避免循环引用）
 */
const isChildOf = (parentId, childId) => {
  const findChild = (id) => {
    const menu = flatMenuList.value.find(m => m.menuId === id);
    if (!menu) return false;
    // 递归检查子节点
    return flatMenuList.value.some(m => m.parentMenuId === id && (m.menuId === childId || findChild(m.menuId)));
  };
  return findChild(parentId);
};

/**
 * 计算子菜单数量
 */
const countChildMenus = (menu) => {
  let count = 0;
  const countChildren = (m) => {
    if (m.children && m.children.length) {
      count += m.children.length;
      m.children.forEach(child => countChildren(child));
    }
  };
  countChildren(menu);
  return count;
};

// ==================== 表单操作 ====================
/**
 * 重置表单
 */
const resetMenuForm = () => {
  menuForm.menuId = '';
  menuForm.name = '';
  menuForm.path = '';
  menuForm.parentMenuId = 0;
  menuForm.permissionCode = '';
  menuForm.component = '';
  menuForm.hidden = false;
  menuForm.metal = '';
  menuForm.icon = '';
  menuForm.sort = 0;
  menuForm.remark = '';
  menuForm.isDeleted = false;

  if (menuFormRef.value) {
    menuFormRef.value.resetFields();
  }
};

/**
 * 打开新增菜单对话框
 */
const handleAddMenu = () => {
  resetMenuForm();
  isEditMode.value = false;
  isSubMenu.value = false;
  currentMenu.value = null;
  showMenuDialog.value = true;
};

/**
 * 打开新增子菜单对话框
 */
const handleAddSubMenu = (row) => {
  resetMenuForm();
  isEditMode.value = false;
  isSubMenu.value = true;
  currentMenu.value = row;
  menuForm.parentMenuId = row.menuId; // 继承父菜单ID
  showMenuDialog.value = true;
};

/**
 * 打开编辑菜单对话框
 */
const editMenu = (row) => {
  resetMenuForm();
  isEditMode.value = true;
  isSubMenu.value = false;
  currentMenu.value = row;

  // 赋值表单（适配接口返回的所有字段）
  Object.assign(menuForm, {
    menuId: row.menuId,
    name: row.name,
    path: row.path,
    parentMenuId: row.parentMenuId,
    permissionCode: row.permissionCode || '',
    component: row.component || '',
    hidden: row.hidden,
    metal: row.metal || '',
    icon: row.icon || '',
    sort: row.sort,
    remark: row.remark || '',
    isDeleted: row.isDeleted || false,
    tenantId: row.tenantId || 0
  });

  showMenuDialog.value = true;
};

/**
 * 保存菜单（新增/编辑）
 */
const saveMenu = async () => {
  try {
    // 表单验证
    await menuFormRef.value.validate();

    // 避免循环引用（编辑时）
    if (isEditMode.value && isChildOf(menuForm.menuId, menuForm.parentMenuId)) {
      ElMessage.warning('不能选择当前菜单的子菜单作为上级菜单');
      return;
    }

    // 构造请求参数（过滤不必要的字段）
    const params = {
      MenuId: menuForm.menuId,
      Name: menuForm.name,
      Path: menuForm.path,
      ParentMenuId: menuForm.parentMenuId,
      PermissionCode: menuForm.permissionCode,
      Component: menuForm.component,
      Hidden: menuForm.hidden,
      Metal: menuForm.metal,
      Icon: menuForm.icon,
      Sort: menuForm.sort,
      Remark: menuForm.remark,
      TenantId: menuForm.tenantId
    };
    console.log('保存菜单参数：', params);
    console.log('isEditMode.value0：', isEditMode.value);

    // 调用接口
    const res = isEditMode.value
        ? await httpRequest.post('menu/update', params)
        : await httpRequest.post('menu/add', {
          Name: menuForm.name,
          Path: menuForm.path,
          ParentMenuId: menuForm.parentMenuId,
          PermissionCode: menuForm.permissionCode,
          Component: menuForm.component,
          Hidden: menuForm.hidden,
          Metal: menuForm.metal,
          Icon: menuForm.icon,
          Sort: menuForm.sort,
          Remark: menuForm.remark,
        });

    if (res.code ===200) {
      ElMessage.success(isEditMode.value ? '菜单编辑成功' : '菜单新增成功');
      showMenuDialog.value = false;
      await getAllMenus(); // 刷新列表
    } else {
      ElMessage.error(res.msg || (isEditMode.value ? '菜单编辑失败' : '菜单新增失败'));
    }
  } catch (error) {
    console.error('保存菜单失败：', error);
    ElMessage.error('保存菜单失败，请重试');
  }
};

/**
 * 处理菜单状态变化（显示/隐藏）
 */
const handleStatusChange = async (row) => {
  try {
    const res = await httpRequest.post('menu/update', {
      menuId: row.menuId,
      hidden: row.hidden
    });
    if (res.code !== 200) { // 修复判断逻辑（原逻辑错误：!res.code ===200 恒为false）
      // 失败时回滚状态
      row.hidden = !row.hidden;
      ElMessage.error(res.msg || '更新菜单状态失败');
    } else {
      ElMessage.success(`菜单已${row.hidden ? '隐藏' : '显示'}`);
    }
  } catch (error) {
    row.hidden = !row.hidden;
    console.error('更新状态失败：', error);
    ElMessage.error('更新菜单状态失败');
  }
};

/**
 * 处理排序变化
 */
const handleSortChange = async (row) => {
  try {
    const res = await httpRequest.post('menu/update', {
      menuId: row.menuId,
      sort: row.sort
    });
    if (res.code !== 200) { // 修复判断逻辑
      ElMessage.error(res.msg || '更新排序失败');
      await getAllMenus(); // 回滚数据
    } else {
      ElMessage.success('排序更新成功');
    }
  } catch (error) {
    console.error('更新排序失败：', error);
    ElMessage.error('更新排序失败');
    await getAllMenus();
  }
};

// ==================== 删除操作 ====================
/**
 * 打开删除确认对话框
 */
const handleDeleteConfirm = (row) => {
  currentMenu.value = row;
  showDeleteDialog.value = true;
};

/**
 * 执行删除（软删除）
 */
const deleteMenu = async () => {
  if (!currentMenu.value?.menuId) return;
  console.log('当前菜单：', currentMenu.value.menuId);

  try {
    const res = await httpRequest.post('menu/delete', {
      menuId: currentMenu.value.menuId
    });

    if (res.code ===200) {
      ElMessage.success('菜单删除成功');
      showDeleteDialog.value = false;
      await getAllMenus();
    } else {
      ElMessage.error(res.msg || '菜单删除失败');
    }
  } catch (error) {
    console.error('删除菜单失败：', error);
    ElMessage.error('删除菜单失败，请重试');
  }
};

// ==================== 对话框辅助 ====================
/**
 * 关闭对话框前的处理
 */
const handleDialogClose = (done) => {
  // 有未保存的修改时提示
  menuFormRef.value?.validateField(['name', 'path'], (errors) => {
    if (errors => errors) {
      ElMessageBox.confirm('表单内容已修改，是否放弃保存？', '提示', {
        confirmButtonText: '放弃',
        cancelButtonText: '保留',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {
        // 取消关闭
      });
    } else {
      done();
    }
  });
};

// ==================== 监听与初始化 ====================
// 监听搜索值变化，实时过滤
watch(searchValue, (newVal) => {
  handleSearch();
});

// 页面初始化
onMounted(async () => {
  await getAllMenus();
});
</script>

<style scoped>
/* 基础布局样式 */
.menu-manage-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 50px);
}

/* 页头样式（RuoYi 风格：面包屑 + 操作栏） */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.breadcrumb {
  font-size: 13px;
}

.operation-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 表格样式 */
.table-card {
  border-radius: 4px;
  border: 1px solid #e9ecef;
  overflow: hidden;
}

.empty-tip {
  padding: 60px 0;
  text-align: center;
}

/* 菜单名称层级样式（删除图标相关样式） */
.menu-name-wrapper {
  display: flex;
  align-items: center;
  height: 36px;
}

.menu-name {
  flex: 1;
}

/* 操作按钮样式（RuoYi 风格：颜色区分） */
.oper-btn {
  padding: 0 8px;
  margin: 0 2px;
}

.add-btn {
  color: #67c23a;
}

.edit-btn {
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}

/* 表单样式 */
.menu-form {
  margin-top: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 10px;
  border-top: 1px solid #f0f2f5;
}

/* 删除提示样式 */
.delete-tip {
  padding: 10px 0;
  line-height: 1.8;
  color: #666;
}

.text-danger {
  color: #f56c6c;
  font-weight: 500;
}

.text-primary {
  color: #409eff;
  font-weight: 500;
}
</style>帮我把新增和编辑分开 一直无法新增 不知道是什么情况